# coding=utf-8
# v0.1.0 新增修改docker insecure-registries， 重启守护进程


import json
import platform
import argparse
import os

system = platform.system()


def default_docker_daemon_json():

    if system == 'Windows':
        return 'C:/ProgramData/Docker/config/daemon.json'
    elif system == 'Linux':
        return '/etc/docker/daemon.json'
    elif system == 'Darwin':
        return '%s/.docker/daemon.json' % os.environ['HOME']


def reload_docker_daemon():
    if system == 'Linux':
        print('systemctl daemon-reload')
        os.system('systemctl daemon-reload')
        print('systemctl reload docker')
        os.system('systemctl reload docker')
        return
    # elif system == 'Darwin':
    raise NotImplementedError(' %s 重新加载docker daemon.json 待实现' % system)


class DockerDaemonJson(object):

    def __init__(self, path):
        self.__json = {}
        self.__path = path
        self.__load(path)
        self.__modified = False

    def __load(self, path):
        if os.path.isfile(path):
            with open(path) as fp:
                self.__json = json.load(fp)

    def __setitem__(self, key, value):
        self.__json[key] = value

    def get(self, key, value=None):
        return self.__json.get(key, value)

    def extends_insecure_registries(self, insecure_registries):
        key = "insecure-registries"
        registries = self.get(key, [])
        registries_set = set(registries)
        for registry in insecure_registries:
            if registry in registries_set:
                print('insecure-registry: %s, 已存在' % registry)
            else:
                print('新增 insecure-registry: %s' % registry)
                registries.append(registry)
                registries_set.add(registry)
                self.__modified = True

        self[key] = registries

    def del_insecure_registries(self, insecure_registries):
        key = "insecure-registries"
        registries = self.get(key, [])
        registries_set = set(registries)
        for registry in insecure_registries:
            if registry in registries_set:
                print('删除 insecure-registry: %s' % registry)
                registries.remove(registry)
                registries_set.remove(registry)
                self.__modified = True
            else:
                print('未找到要删除的域名： insecure-registry: %s' % registry)

        self[key] = registries

    def __str__(self):
        return str(json.dumps(self.__json, indent=4))

    def save(self):
        if self.__modified:
            with open(self.__path, 'w') as fp:
                json.dump(self.__json, fp, ensure_ascii=False, indent=4)
            reload_docker_daemon()
            self.__modified = False


def main():

    parser = argparse.ArgumentParser(description='hosts 修改脚本', usage='-h 查看帮助')

    parser.add_argument('-air', '--add-insecure-registry', action='append',
                        help='新增信任仓库域名, eg: -air "harbor-fz-yfzx.bywin.cn:13029"', default=[])

    parser.add_argument('-dir', '--del-insecure-registry', action='append',
                        help='删除信任仓库域名, eg: -dir "harbor-fz-yfzx.bywin.cn:13029"', default=[])

    parser.add_argument('-f', '--daemon-file',
                        help='docker daemon.json文件, eg, linux默认: -f "/etc/docker/daemon.json"',
                        default=default_docker_daemon_json())

    args = parser.parse_args()

    docker_daemon_json = DockerDaemonJson(args.daemon_file)
    docker_daemon_json.extends_insecure_registries(args.add_insecure_registry)
    docker_daemon_json.del_insecure_registries(args.del_insecure_registry)
    docker_daemon_json.save()

    print(docker_daemon_json)


if __name__ == '__main__':
    main()
    print('执行完成!')
